# -*- coding: utf-8 -*-
import hashlib
import json
import time
import urllib
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '100002': {
        # 'API_KEY': 'bxTWngt82uGQoctC7fviz07ubND7yoCd',
        'API_KEY': 'hCHADXVgNzjMrZeP2h31tuYAR51mwxUp',
        'TRADE_KEY': 'x62uZ6UC3iw5CioYmiWVTujbK2Nb9M18',
        'gateway': 'http://gateway.litaobo.com/gateway/unityOrder/doPay',
        'query_gateway': 'http://gateway.litaobo.com/gateway/query/doQueryOrder',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_sign(parameter, key):
    '''  生成下单签名 '''
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k] != None:
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=' + key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    _LOGGER.info("litaobopay sign str: %s,  sign: %s", s, sign)
    return sign


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("litaobopay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


# 1001 微信扫码
# 1003 支付宝扫码
# 1005 QQ扫码
# 1007 京东扫码
# 1009 银联扫码
# 1011 百度钱包扫码
# 1012 骏卡支付
#
# 2001 微信WAP
# 2002 支付宝WAP
# 2003 QQWAP
#
# 3000 快捷支付绑卡
# 3001 快捷支付
# 3002 银联快捷
# 3003 签约代扣
# 4001 B2C网银
def _get_pay_type(service):
    if service == 'wxpay':
        payType = '2001'
    elif service == 'alipay':
        payType = '2002'
    elif service == 'qq':
        payType = '2003'
    elif service == 'jd':
        payType = '1007'
    else:
        payType = '3001'
    return payType


def _get_str(s, start, end):
    p1 = s.index(start)
    p2 = s.index(end, p1 + len(start))
    if p2 > p1:
        return s[p1 + len(start): p2]
    else:
        return ''


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('version', 'V1.0'),
        ('merNo', app_id),
        ('transTime', time.strftime("%Y%m%d%H%M%S")),
        ('orderNo', str(pay.id)),
        ('amount', '%.2f' % pay_amount),
        ('memberIp', _get_device_ip(info)),
        ('tradeType', _get_pay_type(service)),
        # ('returnUrl', '{}/pay/api/{}/litaobopay/{}/'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('notifyUrl', '{}/pay/api/{}/litaobopay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('goodsId', 'charge'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    parameter_dict[
        'metaOption'] = '''{"s":"WAP","n":"''' + settings.NOTIFY_PREFIX + '''","id":"''' + settings.NOTIFY_PREFIX + '''"}'''
    _LOGGER.info("litaobopay create data : %s", parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("litaobopay create charge rsp data: %s %s", response.status_code, response.text)
    return {'charge_info': urllib.unquote(_get_str(response.text, 'qrcode":"', '"'))}


def _get_return_code(s):
    return s[0:s.index('|')]


def _get_return_sign(s):
    t = s[s.index('|') + 1:]
    return t[t.index('|') + 1:]


# SUCCESS
def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("litaobopay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['orderNo']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('litaobopay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['status'])
    trade_no = data['platOrderNo']
    total_fee = float(data['amount'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '100':
        _LOGGER.info('litaobopay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('version', 'V1.0'),
        ('merNo', app_id),
        ('orderNo', str(pay_id)),
        ('tradeType', '1'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info('litaobopay query data:%s', parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info('litaobopay query rsp:%s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = str(data['status'])
        trade_no = str(data['platOrderNo'])
        total_fee = float(data['amount'])

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == '100':
            _LOGGER.info('litaobopay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                           total_fee, trade_no, extend)
            if res:
                # async notify
                async_job.notify_mch(pay_order.id)
            print("order process successfully. %s" % pay_order.id)
    else:
        _LOGGER.warn('litaobopay data error, status_code: %s', response.status_code)
